/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.condition;

import com.sun.condition.bean.User;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

/**
 * 按照条件给IOC容器中注册组件，在SpringBoot的底层大量使用该注解
 *
 * @Condition;要实现接口Condition
 *
 * 不但可以放在类上也可以放在方法上
 */

@Component
public class MyCondition implements Condition {

    /**
     * @param context  上下文信息
     * @param metadata 相关注解信息
     * @return
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //获取相关环境信息
        Environment environment = context.getEnvironment();
        //获取类加载器
        ClassLoader classLoader = context.getClassLoader();
        //获得Bean工厂
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //获取Bean的注册中心
        BeanDefinitionRegistry registry = context.getRegistry();


        //现在要求window环境下要求注册bena myUser
        //现在向IOC容器中注入一个Bean

        if("windows".contains(environment.getProperty("os.name"))){
            RootBeanDefinition beanDefinition = new RootBeanDefinition(User.class);
            registry.registerBeanDefinition("myUserWindows", beanDefinition);
        }else{
            RootBeanDefinition beanDefinition = new RootBeanDefinition(User.class);
            registry.registerBeanDefinition("myUserLinux", beanDefinition);
        }


        return true;
    }
}
